package edu.mis.modules.orderform;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;

import edu.mis.model.Customer;
import edu.mis.model.Member;
import edu.mis.model.Orderform;
import edu.mis.model.Orderformitem;
import edu.mis.model.Pay;
import edu.mis.model.Recharge;
import edu.mis.model.Room;
import edu.mis.modules.customer.CustomerService;
import edu.mis.modules.member.MemberService;
import edu.mis.modules.orderformitem.OrderformitemService;
import edu.mis.modules.project.ProjectService;
import edu.mis.modules.recharge.RechargeService;
import edu.mis.modules.room.RoomService;
import edu.mis.modules.user.UserService;

public class OrderformController extends Controller{
	
    static UserService userService = new UserService();
    static OrderformService orderformService = new OrderformService();
    static OrderformitemService orderformitemService = new OrderformitemService();
    static ProjectService projectService = new ProjectService();
    static CustomerService customerService = new CustomerService();
    static RoomService roomService = new RoomService();
    static MemberService memberService = new MemberService();
    static RechargeService rechargeService = new RechargeService();
	
	public void index() {
		if(userService.findUserWithRole().equals(1)){
			render("orderform.html");
		}else if(userService.findUserWithRole().equals(2)) {
			render("cashierOrderform.html");
		}else {
			render("noAllAuthority.html");
		}
		
	}
	
	public void list(){
		setAttr("data", orderformService.findAllRecordWithName());
		renderJson();  
	}
	
	/**
	 * 添加订单视图
	 */
	public void add() {
		//render("add.html");  //（默认对应add.html，否则需显性指定，如render("addRole.html")
		render("addfirst.html");
		setAttr("orderformNumber", orderformService.ramdomOrderfromNumber());
		setAttr("login",userService.findLoginUser());
		setAttr("customer",customerService.findAllCustomer());//添加订单前得到所有客户
		setAttr("project",projectService.findAllProject());
		setAttr("user",userService.findUserByroleId(3));
		setAttr("room",roomService.findSpaceRoom(1));
	}
	
	
	/**
	 * 添加订单
	 */
    static int customerId;
	static int i=0;
	static Map<Integer,Orderformitem> orderformitems = new HashMap<Integer,Orderformitem>();
	static Orderform orderform = new Orderform();
	
	public void register(){

		Orderform orderformOther = getModel(Orderform.class);
		Orderformitem orderformitem = getModel(Orderformitem.class);
		
		int control = getParaToInt("control"); 
		if(control==0) {
			i++;
			System.out.println("第"+i+"次添加项目");
			//第一次添加
			if(i==1) {
				if(orderformOther.getCustomerId()!=-1) {
					orderform.setOrderformNumber(orderformOther.getOrderformNumber());
					orderform.setUserId(userService.findLoginUser().getUserId());
					customerId = orderformOther.getCustomerId();
					orderform.setCustomerId(customerId);
					//判断是否存在空值项目
					if(orderformitem.getProjectId()!=-1 && orderformitem.getUserId()!=-1 && orderformitem.getRoomId()!=-1) {
						orderformitem.setOrderformNumber(orderform.getOrderformNumber());
						orderformitem.setSum(projectService.findProjectByProjectId(orderformitem.getProjectId()).getProjectPrice());
						orderformitems.put(i, orderformitem);
						setAttr("result", true); 
						setAttr("msg", "添加项目成功!");	
					}else {
						i--;
						customerId=-1;
						setAttr("result", false); 
						setAttr("msg", "添加项目失败，存在空值项!");	
					}
					
				}else {
					i--;
					setAttr("result", false); 
					setAttr("msg", "添加项目失败，客户为空!");	
				}
				
			}
			
			if(i>1) {
				//判定是否同一个客户
				if(customerId == orderformOther.getCustomerId()) {
					if(orderformitem.getProjectId()!=-1 && orderformitem.getUserId()!=-1 && orderformitem.getRoomId()!=-1) {
						orderformitem.setOrderformNumber(orderform.getOrderformNumber());
						orderformitem.setSum(projectService.findProjectByProjectId(orderformitem.getProjectId()).getProjectPrice());
						orderformitems.put(i, orderformitem);
						setAttr("result", true); 
						setAttr("msg", "添加项目成功!");	
					}else {
						i--;
						setAttr("result", false); 
						setAttr("msg", "添加项目失败，存在空值项!");	
					}
				}else {
					i--;
					setAttr("result", true); 
					setAttr("msg", "添加项目失败，不是同一个客户!");	
				}
			}
		}
		
		
		if (control==1) {
			//第一次不添加，直接提交
			if(i==0) {
				if(orderformOther.getCustomerId()!=-1) {
					orderform.setOrderformNumber(orderformOther.getOrderformNumber());
					orderform.setUserId(userService.findLoginUser().getUserId());
					customerId = orderformOther.getCustomerId();
					orderform.setCustomerId(customerId);
					//判断是否存在空值项目
					if(orderformitem.getProjectId()!=-1 && orderformitem.getUserId()!=-1 && orderformitem.getRoomId()!=-1) {
						orderformitem.setOrderformNumber(orderform.getOrderformNumber());
						orderformitem.setSum(projectService.findProjectByProjectId(orderformitem.getProjectId()).getProjectPrice());
						orderformitems.put(i, orderformitem);
						setAttr("result", true); 
						setAttr("msg", "提交订单成功!");	
					}else {
						customerId=-1;
						setAttr("result", false); 
						setAttr("msg", "提交订单失败，存在空值项!");	
					}
					
				}else {
					
					setAttr("result", true); 
					setAttr("msg", "提交订单失败，客户为空!");	
				}	
			}
			
			//最后提交
			if(i>0) {
				
				if(customerId == orderformOther.getCustomerId()) {
					
					if(orderformitem.getProjectId()!=-1 && orderformitem.getUserId()!=-1 && orderformitem.getRoomId()!=-1) {
						orderformitem.setOrderformNumber(orderform.getOrderformNumber());
						i++;
						orderformitem.setSum(projectService.findProjectByProjectId(orderformitem.getProjectId()).getProjectPrice());
						orderformitems.put(i, orderformitem);
						
					}
					setAttr("result", true); 
					setAttr("msg", "提交订单成功!");

				}else {
					setAttr("result", true); 
					setAttr("msg", "订单提交失败，不是同一个客户!");	
				}
			}
			
			
			orderform.setTime(new Date());
			Integer total=0;
			
			for(Map.Entry<Integer, Orderformitem> entry : orderformitems.entrySet()) {
				total += entry.getValue().getSum();
			}
			orderform.setTotal(total);
			orderform.setPayment(0);
			orderform.setPayId(-1);
			if(orderformService.register(orderform)) {
				
				for(Map.Entry<Integer, Orderformitem> entry : orderformitems.entrySet()) {
					
					entry.getValue().save();
					Room room = roomService.findRoomByRoomId(entry.getValue().getRoomId());
					room.setConditionId(2);
					roomService.updateRoom(room);
				}
				System.out.println("i重置前值为"+i);
				customerId=-1;
				i=0;
				System.out.println("重置的i值为"+i);
				orderformitems = new HashMap<Integer,Orderformitem>();;
				orderform = new Orderform();
			}
		}
		
		if(control==2) {
			System.out.println("i重置前值为"+i);
			customerId=-1;
			i=0;
			System.out.println("重置的i值为"+i);
			orderformitems = new HashMap<Integer,Orderformitem>();
			orderform = new Orderform();
			
			
		}
		renderJson(); 
	}
	
	/**
	 * 支付视图
	 */
	public void auth() {
		setAttr("orderform", orderformService.findOrderformById(getParaToInt("orderformId")));  
		setAttr("pay",Pay.dao.findAll());
	}
	
	/**
	 * 支付
	 */
	public void authorize(){
		int orderformId=this.getParaToInt("orderformId");   
		int payId = this.getParaToInt("payId");
		
		System.out.println("orderformId"+orderformId);
		System.out.println("payId"+payId);
		
		
		
		Orderform orderform = orderformService.findOrderformById(orderformId);
		Customer customer = customerService.findCustomerByCustomerId(orderform.getCustomerId());
		Member member = memberService.findMemberByCustomerNumber(customer.getCustomerNumber());
		List<Orderformitem> projectitems = orderformitemService.findAllOrderformitemByOrderformNumber(orderform.getOrderformNumber());
		
		
		if(orderform.getPayId()==-1) {
			
			if(payId==-1) {
				setAttr("result", false);
				setAttr("msg", "支付失败，请重新选择支付方式!");
			
			}else if(payId==1) {
			//现金支付
				
				orderform.setPayId(payId);
				//会员现金支付
				if(customer.getVip()==1) {
					int payment = (int)(orderform.getTotal()*0.95);
					orderform.setPayment(payment);
					int score = (payment/200)*10;
					member.setMemberScore(member.getMemberScore()+score);
					
					if(orderformService.updateOrderform(orderform) && memberService.updateMember(member)) {
						//支付成功，更新房间状态
						for(int a = 0; a<projectitems.size();a++) {
							Room room = roomService.findRoomByRoomId(projectitems.get(a).getRoomId());
							room.setConditionId(1);
							roomService.updateRoom(room);
						}
						
						
						setAttr("result", true);
						setAttr("msg", "支付成功");
						
					}else {
						setAttr("result", false);
						setAttr("msg", "支付失败，系统出错!");
					}
					
					
				}else {
					//普通客户现金支付	
					orderform.setPayment(orderform.getTotal());
					if(orderformService.updateOrderform(orderform)) {
						
						//支付成功，更新房间状态
						for(int a = 0; a<projectitems.size();a++) {
							Room room = roomService.findRoomByRoomId(projectitems.get(a).getRoomId());
							room.setConditionId(1);
							roomService.updateRoom(room);
						}
						setAttr("result", true);
						setAttr("msg", "支付成功");
					}else {
						setAttr("result", false);
						setAttr("msg", "支付失败，系统出错!");
					}
				}	
			//会员卡支付	
			}else if(payId==2) {
				orderform.setPayId(payId);
				//判断是否会员
				if(customer.getVip()==1) {
					List<Orderformitem> items = orderformitemService.findAllOrderformitemByOrderformNumber(orderform.getOrderformNumber());
					List<Recharge> recharges = rechargeService.findAllRechargeitemByMemberId(member.getMemberId());
					int it = items.size();
		            int re = recharges.size();
		            int i=0,j=0;
		            //一个项目
		            if(it==1) {
		            	int itemProjectId = items.get(i).getProjectId();
		            	for(;j<recharges.size();j++) {
		            		int rechargeProjectId = recharges.get(j).getProjectId();
		            		if(itemProjectId==rechargeProjectId) {
		            			
		            			if(recharges.get(j).getCount()>0) {
		            				recharges.get(j).setCount(recharges.get(j).getCount()-1);
								    break;
		            			}
							}
		            	}
		            	//没匹配到，即没有剩余服务次数，用积分支付
		            	if(re==j) {
		            		int memberScore = member.getMemberScore();
		            		if(memberScore>60) {
		            			member.setMemberScore(memberScore-60);
		            			
		            			memberService.updateMember(member);
		            			orderformService.updateOrderform(orderform);
		            			//支付成功，更新房间状态
								for(int a = 0; a<projectitems.size();a++) {
									Room room = roomService.findRoomByRoomId(projectitems.get(a).getRoomId());
									room.setConditionId(1);
									roomService.updateRoom(room);
								}
		            			
		            			
		            			setAttr("result", true);
		    					setAttr("msg", "刷卡支付成功");
		            		}else {
		            			setAttr("result", true);
		    					setAttr("msg", "刷卡支付失败，服务和积分不足");
		            		}
		            	//匹配到了
		            	}else {
		            		if(rechargeService.updateRecharge(recharges.get(j)) && orderformService.updateOrderform(orderform)){
		            			//支付成功，更新房间状态
								for(int a = 0; a<projectitems.size();a++) {
									Room room = roomService.findRoomByRoomId(projectitems.get(a).getRoomId());
									room.setConditionId(1);
									roomService.updateRoom(room);
								}
		            			setAttr("result", true);
		    					setAttr("msg", "刷卡支付成功");
		            		}else {
		            			setAttr("result", false);
		    					setAttr("msg", "刷卡支付失败，系统错误");
		            		}
		            	}
		            	
		            //多个项目	
		            }else {
		            	
		            	for(;i<items.size();i++) {
							int itemProjectId = items.get(i).getProjectId();
							j=0;
							
							for(;j<recharges.size();j++) {
								
								int rechargeProjectId = recharges.get(j).getProjectId();
								
								if(itemProjectId==rechargeProjectId) {
									
									if(recharges.get(j).getCount()>0) {
									   recharges.get(j).setCount(recharges.get(j).getCount()-1);
									   break;
									}
									
								}
								
							}
							
							
							//只要有一个项目没匹配到，跳出循环，刷卡支付失败
							if(re==j) {
								break;
							}	
		            	}
		            	
		            	//多个项目匹配成功
		            	if(it==i) {
		            		
		            		int t=0;
		            		for(;t<recharges.size();t++) {
		            			rechargeService.updateRecharge(recharges.get(t));
		            		}
		            		if(t==recharges.size() && orderformService.updateOrderform(orderform)) {
		            			//支付成功，更新房间状态
								for(int a = 0; a<projectitems.size();a++) {
									Room room = roomService.findRoomByRoomId(projectitems.get(a).getRoomId());
									room.setConditionId(1);
									roomService.updateRoom(room);
								}
		            			setAttr("result", true);
								setAttr("msg", "刷卡支付成功");
		            		}else {
		            			setAttr("result", false);
								setAttr("msg", "刷卡支付失败，系统错误");
		            		}

		                //多个项目匹配失败	
		            	}else {
		            		setAttr("result", false);
							setAttr("msg", "刷卡支付失败，请充足多个服务的次数");	
		            	}
		            		
		            }
					
				}else {
					setAttr("result", false);
					setAttr("msg", "您不是会员，无法刷卡支付");
				}
				
				
			}else {
				
				setAttr("result", false);
				setAttr("msg", "支付失败，系统出错!");
			}
			
			
		//订单已支付	
		}else {
			setAttr("result", true);
			setAttr("msg", "订单已支付!");
		}

		renderJson();
	}
	
	
	/**
	 * 删除订单
	 * 
	 */
	public void delete() {
		int orderformId = getParaToInt("orderformId");
		int orderformNumber = orderformService.findOrderformById(orderformId).getOrderformNumber();
		System.out.println(orderformNumber);
		
		if(orderformitemService.deleteOrderformitemByOrderformNumber(orderformNumber)) {
			setAttr("result", false);
			setAttr("msg", "删除订单失败!");
		}else {
			if(orderformService.deleteOrderformByOrderformId(orderformId)){
				setAttr("result", true);
				setAttr("msg", "删除订单成功!");
			}else{
				setAttr("result", false);
				setAttr("msg", "删除订单失败!");
			}
		}
		renderJson();
	}
}
